﻿using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System.Diagnostics;

namespace AntDesignProCore.MVC
{
  public class ActionLoggingFilter : IAsyncActionFilter
  {
    private readonly ILogger<ActionLoggingFilter> _logger;

    public ActionLoggingFilter(ILogger<ActionLoggingFilter> logger)
    {
      _logger = logger;
    }

    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
      // 获取登录后的用户信息
      var user = context.HttpContext.User;

      // 获取请求路径
      var requestPath = context.HttpContext.Request.Path.ToString();
      // 获取控制器名称
      var controllerName = context.RouteData.Values["Controller"]?.ToString();
      // 获取 Action 名称
      var actionName = context.RouteData.Values["Action"]?.ToString();
      // 记录请求参数
      var dataJson = JsonConvert.SerializeObject(context.ActionArguments);

      //只记录登录后，admin-api，排除/admin-api/data/notifylist
      var notifylistUrl = "/admin-api/data/notifylist";

      var isLogin = user.Identity?.IsAuthenticated == true;

      //isLogin && 
      if (requestPath.Contains("admin-api") && !requestPath.Equals(notifylistUrl))
      {
        _logger.LogInformation($"---------------------------------------------------------------------------------------------------------------");

        var id = user.FindFirst("id")?.Value;
        var username = user.FindFirst("username")?.Value;
        var name = user.FindFirst("name")?.Value;

        // 记录进入控制器动作的信息
        _logger.LogInformation($"请求路径：{requestPath}");
        _logger.LogInformation($"控制器：{controllerName}");
        _logger.LogInformation($"方法：{actionName}");
        _logger.LogInformation($"参数：{dataJson}");


        AuditContext.Set("RequestPath", requestPath);
        AuditContext.Set("ControllerName", controllerName);
        AuditContext.Set("ActionName", actionName);
        AuditContext.Set("Parameters", dataJson);
        AuditContext.Set("IsLogin", isLogin);

        if (requestPath.Contains("Create") || requestPath.Contains("Update") || requestPath.Contains("Delete"))
        {
          // 将控制器、方法信息存储到 HTTP 请求上下文中
          //var requestContext = _httpContextAccessor.HttpContext.Items;
          //requestContext["ControllerName"] = controllerName;
          //requestContext["ActionName"] = actionName;
          //requestContext["Parameters"] = dataJson;
          //requestContext["isLogin"] = isLogin;
          //_logger.LogInformation($"requestContext：{JsonConvert.SerializeObject(requestContext)}");


        }

        // 开始计时
        var stopwatch = Stopwatch.StartNew();

        // 执行操作方法
        var resultContext = await next();

        // 停止计时
        stopwatch.Stop();

        // 获取耗时（以毫秒为单位）
        var elapsedMilliseconds = stopwatch.ElapsedMilliseconds;

        // 记录日志
        _logger.LogInformation($"请求耗时：{elapsedMilliseconds} ms");


        // 记录返回结果
        //if (resultContext.Result is ObjectResult objectResult)
        //{
        //  _logger.LogInformation($"Response Data: {objectResult.Value}");
        //}
        //else if (context.Result is JsonResult jsonResult)
        //{
        //  _logger.LogInformation($"Response Data (JSON): {jsonResult.Value}");
        //}
        //else if (context.Result is ContentResult contentResult)
        //{
        //  _logger.LogInformation($"Response Content: {contentResult.Content}");
        //}
        //else
        //{
        //  _logger.LogInformation("Response Result: Unhandled type");
        //}
        //_logger.LogInformation($"返回数据：{JsonConvert.SerializeObject(resultContext.Result)}");

        _logger.LogInformation($"---------------------------------------------------------------------------------------------------------------");
      }
      else
      {
        await next();
      }
    }
  }
}
